var $refundTable = $('#refundTable');
var $refundMessTable = $('#refundMessTable');//退款详情的table
var isCaiwu;
var customerOrderBackMoney;//产品列表数据
var getProductOrderId;
var getProductFinalPrice;
// 表格高度
var globalHeight;
var serviceCharge;
var actualRefundAmount;

var refundType;

$(function(){
    globalHeight = $(window).height() - $('#refundTable').offset().top - 54 - 25;
    //判断是不是总财务

    $.ajax({
        url: '/order/isSuperCaiwu',
        type: 'get',
        dataType:"json",
        // contentType:false,
        cache: false,
        async: false,
        success:(function(data) {
            if(data.code == "000000") {
                isCaiwu = data.data
                refundTableInit(data.data);
                $('#refundTable').bootstrapTable('resetView', {height: globalHeight});
            }
        }),
        error:(function() {

        })
    });
    $('#backStatus').selectpicker();
    $('.datepicker').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    })

    // 退款明细弹窗-流程交互相关
    $('.panel-collapse').on('show.bs.collapse', function () {
        $(this).siblings().collapse('hide');
    }).on('shown.bs.collapse', function () {
        $(document).on('click', function (e) {
            var target = $(e.target);
            if(!target.is('a[data-toggle="collapse"]') && !target.is('a[data-toggle="collapse"] *') && !target.is('.panel-collapse') && !target.is('.panel-collapse *')) {
                $('.panel-collapse').collapse('hide');
            }
        });
    });
    $('#refundModal').on('hidden.bs.modal', function () {
        $('.step-anchor').children().removeClass('complete active refuse').find('p').html('-');
    })

    // 服务费+实际退款金额总和判断是否大于申请退款金额
    $('.cost-label input').on('blur', function () {
        var $this = $(this);
        var serviceCharge = Number($('#serviceCharge').val());
        var actualRefundAmount = Number($('#actualRefundAmount').val());
        var applyBackMoney = Number($('#applyBackMoney').html());
        if (serviceCharge + actualRefundAmount > applyBackMoney) {
            $.alert({
                title: '系统提醒',
                content: '服务费和实际退款金额总额不能大于申请退款金额，请重新输入！',
                buttons: {
                    confirm: {
                        text: '确认',
                        btnClass: 'btn-primary',
                        action: function () {
                            $this.val('');
                        }
                    },
                }
            })
        }
    })
})

//防止表头与表格不对齐
$(window).resize(function () {
    $refundTable.bootstrapTable('resetView');
});


/**
 * 全部/周/月/年切换
 * @param time
 */
function selectTime(time) {
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.day').removeClass('active-second');
        $('.customize').removeClass('active-second');
        $("#dateType").val("all");
        $('#customInput').css('display','none');
        $('#startTm').val('');
        $('#endTm').val('');
    }

    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.day').removeClass('active-second');
        $('.customize').removeClass('active-second');
        $("#dateType").val("thisMonth");
        $('#customInput').css('display','none');
        $('#startTm').val('');
        $('#endTm').val('');
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.day').removeClass('active-second');
        $('.customize').removeClass('active-second');
        $("#dateType").val("thisWeek");
        $('#customInput').css('display','none');
        $('#startTm').val('');
        $('#endTm').val('');
    }
    if (time == 'day') {//今天
        $('.day').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.customize').removeClass('active-second');
        $("#dateType").val("day");
        $('#customInput').css('display','none');
        $('#startTm').val('');
        $('#endTm').val('');
    }
    if (time == 'customize') {//自定义
        $('.customize').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.day').removeClass('active-second');
        $("#dateType").val("");
        $('#customInput').css('display','block');
        return;
    }
    $refundTable.bootstrapTable('refreshOptions', {pageNumber: 1,queryParams:queryParams});
}

/**
 * 功能：缩放页面重绘table高度
 * */
$(window).resize(debounce(resizeTable, 500));
function resizeTable() {
    // 计算初始表格高度 = 浏览器高度 - 表格距浏览器顶部高度 - 主体底部padding+margin
    // 注：表格距浏览器顶部高度此处用最外层div获取，解决table垂直滚动时距离
    globalHeight = $(window).height() - $('.bootstrap-table').offset().top - 54 - 25;
    $('#refundTable').bootstrapTable('resetView', {height: globalHeight});
}



//退款表格
function refundTableInit(flag){
    //先销毁表格
    $refundTable.bootstrapTable('destroy');
    $refundTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/order/customerOrderBackMoneyList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'productOrderId',
        idField: 'productOrderId',
        pageSize: 20,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [10,20,50],//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        height: globalHeight,
        columns: [
            {title: '主键', field: 'productOrderId', visible: false},
            /*{title: '全选', field: 'checked', align: 'center', checkbox: true, valign: 'middle',width: '6%'},*/
            {title: '订单编号',field: 'orderNumber', align: 'left', valign: 'middle'},
            {title: '申请人', field: 'userName', align: 'left', valign: 'middle'},
            {title: '所属分公司', field: 'companyName', align: 'left', valign: 'middle' },
            {title: '退款状态', field: 'backStatus', align: 'right', valign: 'middle',formatter:function backStatusForm(value){
                if(value == 0){
                    return '<span class=\'label label-info-light\'>审核中</span>'
                }else if(value == 1){
                    return '<span class=\'label label-warning-light\'>未通过</span>'
                }else if(value == 2){
                    return '<span class=\'label label-success-light\'>已通过</span>'
                }
            }},
            {title: '退款类型', field: 'refundType', align: 'right', valign: 'middle',formatter:function backStatusForm(value){
                    if(value == 0){
                        return '<span class=\'label label-info-light\'>订单产品退款</span>'
                    }else if(value == 1){
                        return '<span class=\'label label-warning-light\'>余额退款</span>'
                    }
                }},
            {title: '服务费', field: 'serviceMoney', align: 'left', valign: 'middle' },
            {title: '退款金额', field: 'applyBackMoney', align: 'center', valign: 'middle' },
            {title: '申请日期', field: 'createTm', align: 'center', valign: 'middle' },
            {title: '审核日期', field: 'updateTm', align: 'center', valign: 'middle' },
            {title: '退款日期', field: 'backDate', align: 'center', valign: 'middle' },
            {title: '审核人', field: 'examineUserName', align: 'center', valign: 'middle' },
            {title: '操作', field: 'royaltyStatus', align: 'right', valign: 'middle',formatter: genderOpt },
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.bs = 0;
    params.adoptSituation = accountType;

    params.orderNumber = $('#orderNumberSearch').val();
    params.applyStart = $('#startTm').val();
    params.applyEnd = $('#endTm').val();
    params.dateType = $('#dateType').val();
    return params;
}

function advancedQueryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.bs = 0;
    params.adoptSituation = accountType;

    params.createTm = $('#createTm').val();
    params.companyName  = $('#branch_office').val();
    params.userName = $('#all').val();
    params.shName = $('#reviewer').val();
    params.applyStart = $('#startTm').val();
    params.applyEnd = $('#endTm').val();
    params.dateType = $('#dateType').val();
    params.backStatus = $('#backStatus').val();
    return params;
}

function searchReturnMoneyList(num){
    if(num == 1){
        $refundTable.bootstrapTable('refreshOptions', {pageNumber: 1,queryParams:queryParams});
    }else{
        $refundTable.bootstrapTable('refreshOptions', {pageNumber: 1,queryParams:advancedQueryParams});
    }
}


/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {


    return [
        // '<button class="btn btn-default" id="refund"><i class="mdi mdi-replay"></i>退款</button>',
        '<button class="btn btn-default" id="detail" onclick="chekBtn(\'' + row.orderBackMoneyId + '\',\''+row.productOrderId+'\',\''+row.refundType+'\',\''+row.backStatus+'\')"><i class="mdi mdi-eye"></i>查看</button>',
    ].join('');
}

//未通过查看弹框
function noPass() {
    $.alert('请联系客服部')
}

//审核弹框
function chekBtn(orderBackMoneyId,productOrderId,state,backStatus){
    refundType = state;
    if(backStatus == 0){
        $('.isShow_Audit').show();
        $('#isSubmit').show()
    }else if(backStatus == 1){
        $('.isShow_Audit').hide();
        $('#isSubmit').hide()
    }else if(backStatus == 2){
        $('.isShow_Audit').hide();
        $('#isSubmit').hide()
    }
    if(state == 0){
        var data = {
            orderBackMoneyId,
            productOrderId,
        }
        oderDetail('/order/customerOrderBackMoneyDetail',data,state)
        // oderDetail(orderBackMoneyId,productOrderId);
        $('#orderProductDetails').show();
        $('#balanceRefundDetails').hide();
        $('#refundMessTableModal').show();
        $('#wlbActionBox').show()

    }else{
        var data1 = {
            orderBackMoneyId,
        }
        oderDetail('/order/balanceBackMoneyDetail',data1,state)
        $('#orderProductDetails').hide();
        $('#balanceRefundDetails').show()
        $('#refundMessTableModal').hide()
        $('#wlbActionBox').hide()
    }

    getProductOrderId = productOrderId
    // oderDetail(orderBackMoneyId,productOrderId);
    $('#not_audit').prop('checked',true);
    $('.amount').attr('disabled',true)
    $('#refundModal').modal('show');
    $('#serviceCharge').val('');
    $('#actualRefundAmount').val('')
    $('#actualRefundRemark').val('')
    // refundMessTableInit(orderBackMoneyId,productOrderId)
}

//退款详情
function statusTransform (type) {
    switch (type) {
        case 0:
            return '审核中';
            break;
        case 1:
            return '未通过';
            break;
        case 2:
            return '通过';
            break;
        case null:
            return '-';
            break;
    }
}
function productStatus(type) {
    if (type == 1) {
        return '退款';
    } else if (type == 0) {
        return '正常';
    } else {
        return '';
    }
}
function  oderDetail(url,data,state) {
    $.ajax({
        url: url,
        type: 'POST',
        // data:{
        //     orderBackMoneyId:orderBackMoneyId,
        //     productOrderId:productOrderId,
        // },
        data:data,
        success:(function(data) {
            if(data.code == "000000") {
                // 状态处理
                var examineData = data.data.orderBackMoneyExamine;
                if (examineData) {
                    $('.step-group').show();
                    // 判断当前登录用户是否已通过，通过则禁用审批操作
                    if (examineData.adoptSituation != accountType) {
                        $('#audit').prop('checked', true);
                        $('input[name="whetherIncludedAchievement"]').prop('disabled', true);
                        $('.success-label, #refundModal .modal-footer .btn-primary').hide();
                    } else {
                        $('input[name="whetherIncludedAchievement"]').prop('disabled', false);

                        if(data.status == 1 || data.status == 2){
                            $('.success-label, #refundModal .modal-footer .btn-primary').hide();
                        }else if(data.status == 0){
                            $('.success-label, #refundModal .modal-footer .btn-primary').show();
                        }
                    }

                    $('#adoptSituation').val(examineData.adoptSituation);

                    var statusActiveIndex = examineData.adoptSituation;

                    $('.step-anchor li').each(function (index, element) {
                        var $element = $(element);
                        $element.children().attr('data-toggle', 'collapse');
                        if (index == statusActiveIndex) {
                            // 当前状态
                            $element.addClass('active');
                            if (data.data.status == 1) {
                                $element.addClass('refuse');
                            } else {
                                $element.children().removeAttr('data-toggle');
                            }
                        } else if (index < statusActiveIndex) {
                            // 已完成状态
                            $element.addClass('complete');
                        } else {
                            $element.children().removeAttr('data-toggle');
                        }
                    });
                    $('#fzStatus').html(statusTransform(examineData.fzExamineStatus));
                    $('#kfStatus').html(statusTransform(examineData.kfExamineStatus));
                    $('#xzStatus').html(statusTransform(examineData.xzExamineStatus));
                    $('#wlbStatus').html(statusTransform(examineData.wlbExamineStatus));
                    $('#cwStatus').html(statusTransform(examineData.cwExamineStatus));

                    // 分总信息
                    $('#fzName').html(examineData.fzExamineUserName || '-');
                    $('#fzTime').html(examineData.fzExamineTm == null ? '-' : new Date(examineData.fzExamineTm).Format("yyyy-MM-dd hh:mm:ss"));
                    $('#fzRemarks').html(examineData.fzExamineRemarks || '-');
                    // 客服信息
                    $('#kfName').html(examineData.kfExamineUserName || '-');
                    $('#kfTime').html(examineData.kfExamineTm == null ? '-' : new Date(examineData.kfExamineTm).Format("yyyy-MM-dd hh:mm:ss"));
                    $('#kfRemarks').html(examineData.kfExamineRemarks || '-');
                    // 销总信息
                    $('#xzName').html(examineData.xzExamineUserName || '-');
                    $('#xzTime').html(examineData.xzExamineTm == null ? '-' : new Date(examineData.xzExamineTm).Format("yyyy-MM-dd hh:mm:ss"));
                    $('#xzRemarks').html(examineData.xzExamineRemarks || '-');
                    // 网络部信息
                    $('#wlbName').html(examineData.wlbExamineUserName || '-');
                    $('#wlbTime').html(examineData.wlbExamineTm == null ? '-' : new Date(examineData.wlbExamineTm).Format("yyyy-MM-dd hh:mm:ss"));
                    // 网络部信息-产品明细
                    if(state == 0){
                        if (data.data.customerOrderBackMoney[0].orderStatus == 2 && data.data.orderBackMoneyExamine.adoptSituation > 2) {
                            var cardData = data.data.card;
                            // 会员卡
                            var mememberCardDom = '';
                            if (cardData.customerProductDetailMemberCard != null && cardData.customerProductDetailMemberCard.length) {
                                mememberCardDom += '<h6>会员卡</h6>';
                                mememberCardDom += '<ul><li><span>会员卡号</span><span>会员卡密码</span><span>状态</span></li>';
                                for (let i = 0; i < cardData.customerProductDetailMemberCard.length; i++) {
                                    mememberCardDom += '<li><span>'
                                        + cardData.customerProductDetailMemberCard[i].memberCardNumber + '</span><span>'
                                        + cardData.customerProductDetailMemberCard[i].memberCardPassword + '</span><span>'
                                        + (cardData.customerProductDetailMemberCard[i].voidStatus == 0 ? '正常' : '作废') + '</span></li>';
                                }
                                mememberCardDom += '</ul>';
                            }
                            // 税法直通车
                            var throughRrainCard = '';
                            if (cardData.taxList != null && cardData.taxList.length) {
                                throughRrainCard += '<h6>税法直通车</h6>';
                                throughRrainCard += '<ul><li><span>会员卡号</span><span>会员卡密码</span><span>状态</span></li>';
                                for (let i = 0; i < cardData.taxList.length; i++) {
                                    throughRrainCard += '<li><span>'
                                        + cardData.taxList[i].memberCardNumber + '</span><span>'
                                        + cardData.taxList[i].memberCardPassword + '</span><span>'
                                        + (cardData.taxList[i].deleteStatus == 0 ? '正常' : '已删除') + '</span></li>';
                                }
                                throughRrainCard += '</ul>';
                            }
                            // 兑换码
                            var exchangeCodeCard = '';
                            if (cardData.codeList != null && cardData.codeList.length) {
                                exchangeCodeCard += '<h6>兑换码</h6>';
                                exchangeCodeCard += '<ul><li><span>兑换码</span><span>兑换码名称</span><span>状态</span></li>';
                                for (let i = 0; i < cardData.codeList.length; i++) {
                                    exchangeCodeCard += '<li><span>'
                                        + cardData.codeList[i].exchangeCodeCrmId + '</span><span>'
                                        + cardData.codeList[i].exchangeCodeName + '</span><span>'
                                        + (cardData.codeList[i].deleteStatus == 0 ? '正常' : '已删除') + '</span></li>';
                                }
                                exchangeCodeCard += '</ul>';
                            }
                            // 云顾问卡
                            var cloudCard = '';
                            if (cardData.yunList != null && cardData.yunList.length) {
                                cloudCard += '<h6>兑换码</h6>';
                                cloudCard += '<ul><li><span>云顾问卡号</span><span>密码</span><span>状态</span></li>';
                                for (let i = 0; i < cardData.yunList.length; i++) {
                                    cloudCard += '<li><span>'
                                        + cardData.yunList[i].yunCard + '</span><span>'
                                        + cardData.yunList[i].yunPassword + '</span><span>'
                                        + (cardData.yunList[i].deleteStatus == 0 ? '正常' : '已删除') + '</span></li>';
                                }
                                cloudCard += '</ul>';
                            }
                            // 充值卡
                            var rechargeCard = '';
                            if (cardData.rechargeCodeList != null && cardData.rechargeCodeList.length) {
                                rechargeCard += '<h6>兑换码</h6>';
                                rechargeCard += '<ul><li><span>充值卡卡号</span><span>充值码密码</span><span>状态</span></li>';
                                for (let i = 0; i < cardData.rechargeCodeList.length; i++) {
                                    rechargeCard += '<li><span>'
                                        + cardData.rechargeCodeList[i].rechargeCodeCrmId + '</span><span>'
                                        + cardData.rechargeCodeList[i].rechargeCodePassword + '</span><span>'
                                        + (cardData.rechargeCodeList[i].deleteStatus == 0 ? '正常' : '已删除') + '</span></li>';
                                }
                                rechargeCard += '</ul>';
                            }
                            // 优惠劵
                            var coupon = '';
                            if (cardData.couponsList != null && cardData.couponsList.length) {
                                coupon += '<h6>兑换码</h6>';
                                coupon += '<ul><li><span>优惠劵码</span><span>优惠劵名称</span><span>状态</span></li>';
                                for (let i = 0; i < cardData.couponsList.length; i++) {
                                    coupon += '<li><span>'
                                        + cardData.couponsList[i].couponCodeCrmId + '</span><span>'
                                        + cardData.couponsList[i].couponName + '</span><span>'
                                        + (cardData.couponsList[i].deleteStatus == 0 ? '正常' : '已删除') + '</span></li>';
                                }
                                coupon += '</ul>';
                            }
                        }
                    }
                    var actionDom = mememberCardDom + throughRrainCard + exchangeCodeCard + cloudCard + rechargeCard + coupon;
                    $('#wlbAction').html(actionDom || '-');
                    $('#wlbRemarks').html(examineData.wlbExamineRemarks || '-');
                    // 财务信息
                    $('#cwName').html(examineData.cwExamineUserName || '-');
                    $('#cwTime').html(examineData.cwExamineTm  == null ? '-' : new Date(examineData.cwExamineTm).Format("yyyy-MM-dd hh:mm:ss"));
                    $('#cwRemarks').html(examineData.cwExamineRemarks || '-');
                } else {
                    // $('.step-anchor li').removeClass('complete active').find('p').html('-');
                    // $('.step-anchor li a').removeAttr('data-toggle');
                    $('.step-group').hide();
                }
                if(state == 0){
                    refundMessTableInit(data.data.customerOrderBackMoney)

                    $('#serialNumber').text(data.data.order.orderNumber);
                    $('#contractNumber').text(data.data.order.contractNumber)
                    if(data.data.order.orderStatus == 1){
                        $('#orderState').text('等待回款')
                    }else if(data.data.order.orderStatus == 2){
                        $('#orderState').text('已完成')
                    }else if(data.data.order.orderStatus == 3){
                        $('#orderState').text('作废')
                    }else if(data.data.order.orderStatus == 4){
                        $('#orderState').text('部分回款')
                    }
                    $('#customerName').text(data.data.order.customerName)
                    $('#oderUser').text(data.data.order.userName)
                    console.log(data.data.order.companyName)
                    $('#branchOffice').text(data.data.order.companyName)
                    $('#createTime').text(data.data.order.createTm)
                    $('#refundRemark').text(data.data.sqbz)
                    $('#applyBackMoney').text(data.data.customerOrderBackMoney[0].applyBackMoney)
                    $('#royaltyStatus').text(data.data.royaltyStatus)
                    customerOrderBackMoney = data.data.customerOrderBackMoney[0]
                    getProductFinalPrice = data.data.customerOrderBackMoney[0].productFinalPrice
                    $('#actualRefundAmountVal').val(data.data.customerOrderBackMoney[0].backMoney || 0)
                    $('#customerNumber').html(data.data.customerOrderBackMoney[0].customerNumber || '-');
                    if (data.data.order.refundType == 0) {
                        $('#refundType').html('订单产品');
                    }
                    if (data.data.order.refundType == 1) {
                        $('#refundType').html('余额');
                    }

                    serviceCharge = data.data.customerOrderBackMoney[0].serviceMoney || 0;
                    actualRefundAmount = data.data.customerOrderBackMoney[0].backMoney || data.data.customerOrderBackMoney[0].applyBackMoney;
                }else{
                    $('#customerId').val(data.data.balanceBackMoneyVO.customerId)
                    $('#refundCustomerName').text(data.data.balanceBackMoneyVO.customerName)
                    $('#refundCustomerNumber').text(data.data.balanceBackMoneyVO.customerNumber)
                    if(data.data.balanceBackMoneyVO.refundType == 0){
                        $('#balanceRefundType').text('订单产品退款')
                    }else if(data.data.balanceBackMoneyVO.refundType == 1){
                        $('#balanceRefundType').text('余额退款')
                    }
                    $('#refundMoney').text(data.data.balanceBackMoneyVO.applyBackMoney)
                    $('#refundMask').text(data.data.balanceBackMoneyVO.sqbz)
                    $('#refundCreate').text(data.data.balanceBackMoneyVO.createTm)
                    $('#refundBranchOffice').text(data.data.balanceBackMoneyVO.companyName)
                    $('#refundPeople').text(data.data.balanceBackMoneyVO.userName)
                    $('#refundRemark').text(data.data.balanceBackMoneyVO.sqbz || '-')
                    $('#shbz').text(data.data.balanceBackMoneyVO.shbz || '-')
                    customerOrderBackMoney = data.data.balanceBackMoneyVO
                    if (data.data.balanceBackMoneyVO) {
                        $('#applyBackMoney').text(data.data.balanceBackMoneyVO.applyBackMoney)
                        $('#serviceMoney').text(data.data.balanceBackMoneyVO.serviceMoney)
                        $('#backMoney').text(data.data.balanceBackMoneyVO.backMoney)
                        $('#actualRefundAmountVal').val(data.data.balanceBackMoneyVO.backMoney || 0)
                    } else {
                        $('#applyBackMoney, #serviceMoney, #backMoney').html('-');
                    }
                    serviceCharge = data.data.balanceBackMoneyVO.serviceMoney || 0;
                    actualRefundAmount = data.data.balanceBackMoneyVO.backMoney || data.data.balanceBackMoneyVO.applyBackMoney;
                }

            }
        }),
        error:(function() {

        })
    });
}

//退款table
// function refundMessTableInit(orderBackMoneyId,productOrderId){
function refundMessTableInit(data){
    //先销毁表格
    $refundMessTable.bootstrapTable('destroy');
    $refundMessTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        // url: '/order/customerOrderBackMoneyDetail',//请求地址
        // method: 'post',//请求方式
        // contentType: "application/x-www-form-urlencoded",//请求内容类型
        data,
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: false,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'productOrderId',
        idField: 'productOrderId',
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [5,10,15,20],//可供选择的每页的行数
        queryParams:function(params){
            params.orderBackMoneyId = orderBackMoneyId;
            params.productOrderId = productOrderId;
            return params;
        },//查询参数
        columns: [
            {title: '主键', field: 'productOrderId', visible: false},
            {title: '产品名称',field: 'productName', align: 'left', valign: 'middle'},
            {title: '产品原价', field: 'productOriginalPrice', align: 'left', valign: 'middle'},
            {title: '会员价', field: 'productMemberPrice', align: 'left', valign: 'middle'},
            {title: '产品成交价', field: 'productFinalPrice', align: 'right', valign: 'middle'},
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data.customerOrderBackMoney,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

//设置输入框限制
function auditState(){
    var backStatus = $("input[name='whetherIncludedAchievement']:checked").val();
    if(backStatus == 2){
        // $('.amount').attr('disabled',false);
        $('#serviceCharge').val(serviceCharge);
        $('#actualRefundAmount').val(actualRefundAmount);
        if (accountType == 1) {
            $('#serviceCharge, #actualRefundAmount').prop('disabled', false);
            $('#costLabel .control-label').addClass('label-required');
        }
    }else{
        // $('.amount').attr('disabled',true)
        $('#serviceCharge').val('');
        $('#actualRefundAmount').val('')
        if (accountType == 1) {
            $('#serviceCharge, #actualRefundAmount').prop('disabled', true);
            $('#costLabel .control-label').removeClass('label-required');
        }
    }
}

// //计算实际退款金额
// function  calculateRefundNumber(){
//     $('#actualRefundAmount').val($('#applyBackMoney').text() - $('#serviceCharge').val())
// }

//提交
function submitRefund(){
    if($("input[name='whetherIncludedAchievement']:checked").val() == 1){
        if($('#actualRefundRemark').val() == ''){
            $.alert('审核备注不能为空')
            return;
        }
        $('#promptFailure').modal('show');
    }else  if($("input[name='whetherIncludedAchievement']:checked").val() == 2){
        // 客服审核时，退款金额必填项提醒
        if (accountType == 1 && $('#actualRefundAmount').val() == '') {
            $.alert({
                title: '系统提醒',
                content: '实际退款金额不能为空，请重新输入！'
            });
            return;
        }

        $('#refundNumber').text($('#actualRefundAmount').val()+'￥')
        /*if(Number($('#serviceCharge').val()) > Number($('#applyBackMoney').text())){
            $.alert('服务费不能大于申请退费金额')
            return;
        }
        if( $('#serviceCharge').val() == ''){
            $.alert('服务费不能为空')
            return;
        }
        if( $('#actualRefundAmount').val() == ''){
            $.alert('实际退费金额不能为空')
            return;
        }
        if( $('#actualRefundAmount').val() > getProductFinalPrice){
            $.alert('实际退费金额不能大于成交价')
            return;
        }
        if($('#actualRefundRemark').val() == ''){
            $.alert('审核备注不能为空')
            return;
        }*/
        $('#promptSuccess').modal('show');

    }

}

function review(){
    var jsonData = {
        orderBackMoneyId: customerOrderBackMoney.orderBackMoneyId,  //退款id
        backNumber: customerOrderBackMoney.backNumber, //退款编号
        productOrderId: customerOrderBackMoney.productOrderId,  //订单id
        productOrderDetailId: customerOrderBackMoney.productOrderDetailId, //订单产品明细id
        productName: customerOrderBackMoney.productName,  //产品名称
        productOriginalPrice: customerOrderBackMoney.productOriginalPrice,  //原价
        productUnitPrice: customerOrderBackMoney.productUnitPrice,  //单价
        productMemberPrice: customerOrderBackMoney.productMemberPrice,  //会员价
        productPreferentialPrice: customerOrderBackMoney.productPreferentialPrice,  //优惠价
        productFinalPrice: customerOrderBackMoney.productFinalPrice,  //成交价
        applyBackMoney: customerOrderBackMoney.applyBackMoney,  //申请退款金额
        backMoney: $('#actualRefundAmount').val() || $('#actualRefundAmountVal').val(),  //实际退款金额
        serviceMoney: $('#serviceCharge').val() || 0,  //服务费
        backStatus: $('input[name="whetherIncludedAchievement"]:checked').val(),  //退款状态 0审核中 1未通过 2已退款
        finishOrderProductNum: customerOrderBackMoney.finishOrderProductNum,
        shbz: $('#actualRefundRemark').val(),
        adoptSituation: $('#adoptSituation').val(),
    }
    console.log(jsonData)
    // return;
    $.ajax({
        url: ' /order/orderRefundFinance',
        type: 'POST',
        contentType: "application/json;charset=utf-8",
        data:JSON.stringify(jsonData),
        success:(function(data) {
            if(data.data == "SUCCESS") {
                refundTableInit(isCaiwu)
            }else{
                $.alert(data.data);
            }
        }),
        error:(function() {

        })
    });
}

//余额退款
function balanceRefund(){
    var jsonData = {
        orderBackMoneyId: customerOrderBackMoney.orderBackMoneyId,  //退款id
        backNumber: customerOrderBackMoney.backNumber, //退款编号
        applyBackMoney: customerOrderBackMoney.applyBackMoney,  //申请退款金额
        backMoney: $('#actualRefundAmount').val()  || $('#actualRefundAmountVal').val(),  //实际退款金额
        serviceMoney: $('#serviceCharge').val() || 0,  //服务费
        backStatus: $('input[name="whetherIncludedAchievement"]:checked').val(),  //退款状态 0审核中 1未通过 2已退款
        adoptSituation: $('#adoptSituation').val(),
        shbz: $('#actualRefundRemark').val(),
        customerId:$('#customerId').val(),
    }
    console.log(jsonData)
    // return;
    $.ajax({
        url: '/order/balanceRefundFinance',
        type: 'POST',
        contentType: "application/json;charset=utf-8",
        data:JSON.stringify(jsonData),
        success:(function(data) {
            if(data.data == "SUCCESS") {
                refundTableInit(isCaiwu)
            }else{
                $.alert(data.data);
            }
        }),
        error:(function() {

        })
    });
}


//确定按钮刷新表格
function sureBtn(num){
    if(num == 1){
        $('#promptFailure').modal('hide');
        $('#refundModal').modal('hide');
        if(refundType == 0){
            review()
        }
        if(refundType == 1){
            balanceRefund()
        }
    }else if(num == 2){
        $('#promptSuccess').modal('hide');
        $('#refundModal').modal('hide');
        if(refundType == 0){
            review()
        }
        if(refundType == 1){
            balanceRefund()
        }
    }

    refundTableInit(isCaiwu)
}


function cancel(){
    $('#refundModal').modal('hide');
    // refundTableInit(isCaiwu);
}

function clearAllData(){
    $('#branch_office').val('')
    $('#all').val('')
    $('#createTm').val('')
    $('#reviewer').val('')
    $('#backStatus').val('').selectpicker('refresh');
    $refundTable.bootstrapTable('refreshOptions', {pageNumber: 1,queryParams:queryParams});
}
